/*
 * This file is part of J2ME VNC.
 *
 * Copyright (c) 2003 Michael Lloyd Lee
 *
 * J2ME VNC is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * J2ME VNC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with J2ME VNC; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package tk.wetnet.j2me.vnc;

import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.TextField;

import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordEnumeration;

/** The About and Advanced Settings MIDlet.
 * To reduce the run-time memory requirements of the main MIDlet, 
 * the about screen and the advanced settings are combined into a
 * separate MIDlet. 
 * @author Michael Lloyd Lee
 * @version 1.0.0
 * @todo Rewrite Macro Maker
 */

public class About extends MIDlet  
    implements CommandListener {
    private Command exit = new Command( "#exit#", Command.EXIT,   0 );
    private Command delete = new Command( "#reset_hosts#", Command.SCREEN, 1 );
    private Command gpl = new Command( "#gpl#", Command.SCREEN, 1);
    private Command mit = new Command( "#mit#", Command.SCREEN, 1);
    private Command tranlators = new Command( "#translators#", Command.SCREEN,
					      0);
    private Command buts = new Command( "#buts#",Command.SCREEN, 1);

    private Command editCmds = new Command( "#edit_cmds#", Command.SCREEN, 1 );

    private Command back = new Command( "#back#", Command.BACK, 0 );

    private Command update = new Command( "#update#", Command.ITEM, 0 );
    private Command add = new Command( "#add#", Command.OK, 0 );

    /** For getHeight()/getWidth()
     */
    private VNCCanvas c = new VNCCanvas(); // why ohh why arn't they static?

    private Form about = new Form( "#about#" );
    private Image ab = null; 

    private Alert gplAlert = null;
    private Alert mitAlert = null;
    private Alert tranAlert = null;
    private Alert butsAlert = null;
 
    private Form commandForm = null;

    private RecordStore rs;

    /** The name of the Macro */
    private TextField name = new TextField( "#name#", "", 255, TextField.ANY );
    /** The Macro string */
    private TextField macro = new TextField( "#macro#", "", 255, 
					     TextField.ANY );

    private HostCommand currentID = null;

    public About() {
	super();
	
	try {
	    ab = Image.createImage( "/VNC.png" );	    
	    about.append( ab );
	} catch( java.io.IOException t ) { 
	}
	about.append( "#aboutstr#\n#http#\n#sprocketcog#\n#mark#\n#konrad#\n#me#" );

	gplAlert = new Alert( "#gpl#", "#gplstr#", ab,  AlertType.INFO );
	butsAlert = new Alert( "#buts#", 
			       "#up#" + c.getKeyName( c.getKeyCode(c.UP))
			       + "\n#down#" + c.getKeyName
			       ( c.getKeyCode(c.DOWN))
			       + "\n#left#" + c.getKeyName
			       ( c.getKeyCode(c.LEFT))    
			       + "\n#right#" + c.getKeyName
			       ( c.getKeyCode(c.RIGHT))
			       + "\n#fire#" + c.getKeyName
			       ( c.getKeyCode(c.FIRE))
			       + "\n#game_a#" + c.getKeyName
			       ( c.getKeyCode(c.GAME_A))

			       , ab,  AlertType.INFO );
	mitAlert = new Alert( "#mit#", "#mitstr#", ab,  AlertType.INFO ); 
	tranAlert = new Alert( "#translators#", "#thanks#\n"
			       + "Steffen Menne\n"
			       + "for the German version\n"
			       + "Angela Antoniou\n"
			       + "for the Greek version\n"
			       + "Nythil\n"
			       + "for the Polish version\n"
			       + "Emeric Laroche\n"
			       + "for the French version",
			       ab,  AlertType.INFO ); 

	gplAlert.setTimeout( Alert.FOREVER );
	mitAlert.setTimeout( Alert.FOREVER );
	tranAlert.setTimeout( Alert.FOREVER );
	butsAlert.setTimeout( Alert.FOREVER );

	commandForm = new Form( "#edit_cmds_title#" );
	commandForm.append( name );
	commandForm.append( macro );
	commandForm.setCommandListener( this );

	commandForm.addCommand( back );
	commandForm.addCommand( add );
	
	// TODO: Fix exception handling!
	try {
	    rs = RecordStore.openRecordStore( "cmds", true );
	    if( rs.getNumRecords() == 0 ) {
		byte[] s = "Ctrl Alt Del|<\\c<\\a!\\d>\\a>\\c".getBytes();
		rs.addRecord( s, 0, s.length );
	    }
	    

	    RecordEnumeration re = rs.enumerateRecords( null, null, false );
	    while( re.hasNextElement() ) {
		int id = re.nextRecordId();
		String current = new String( rs.getRecord(id) );
		String title = current;
		if( current.indexOf( "|" ) > 0 ) {
		    title = current.substring(0, current.indexOf( "|" ) );
		}
		HostCommand cm = new HostCommand( title, 
						  Command.ITEM, 10, id );
		commandForm.addCommand( cm );
	    }
	} catch( javax.microedition.rms.RecordStoreException t ) {
	    System.err.println( "VNC() : t " + t.toString() );
	    t.printStackTrace();
	}

	/***
	 * My bad haiku
	 * Memory of Net Positive
	 * it is in.
	 ***/
	about.addCommand( exit );
	about.addCommand( gpl );
	about.addCommand( buts );
	about.addCommand( mit );
	about.addCommand( editCmds );
	about.addCommand( tranlators );
	about.addCommand( delete );
	about.setCommandListener( this );

    }

    public void commandAction(Command c, Displayable d) {
	if( d == commandForm ) {
	    // TODO: Fix exception handling!
	    try {
		if( c == back ) {
		    Display.getDisplay( this ).setCurrent( about ) ;
		} else if( c == add ) {
		    byte[] s = (name.getString().replace( '|', 'p') 
				+ "|"
				+ macro.getString().replace( '|', 'p'))
			.getBytes();
		    int id = rs.addRecord( s, 0, s.length );
		    HostCommand hc = new HostCommand( name.getString()
						      .replace( '|', 'p'), 
						      Command.ITEM, 10, id );
		    commandForm.addCommand( hc );
		    commandForm.removeCommand( add );
		    commandForm.addCommand( update );
		    currentID = hc;		
		} else if(c == update ) {
		    byte[] s = (name.getString().replace( '|', 'p') 
				+ "|"
				+ macro.getString().replace( '|', 'p'))
			.getBytes();
		    rs.setRecord( currentID.id, s, 0, s.length );
		    commandForm.removeCommand( currentID );
		    currentID = new HostCommand( name.getString()
						 .replace( '|', 'p'), 
						 Command.ITEM, 10, 
						 currentID.id );
		    commandForm.addCommand( currentID );
		    
		} else if( c instanceof HostCommand ) {
		    String tmp = new String( rs.getRecord( ((HostCommand)c)
							   .id ) );
		    name.setString( tmp.substring(0, tmp.indexOf( "|" ) ) );
		    macro.setString( tmp.substring
				     ( tmp.indexOf( "|" ) + 1, 
				       tmp.length()) );
		    commandForm.removeCommand( add );
		    commandForm.addCommand( update );
		    currentID = (HostCommand)c;
		}
	    } catch( Throwable t ){
		System.err.println( t );
		Display.getDisplay( this ).setCurrent
		    ( new Alert( "Error", t.toString(), null, 
				 AlertType.ERROR ), commandForm );
		
	    }
	} else if( d == about ) {
	    if( c == exit ) {
		notifyDestroyed();
	    } else if( c == gpl ) {  
		Display.getDisplay( this ).setCurrent( gplAlert );
	    } else if( c == mit ) {  
		Display.getDisplay( this ).setCurrent( mitAlert );
	    } else if( c == tranlators ) {  
		Display.getDisplay( this ).setCurrent( tranAlert );
	    } else if( c == editCmds ) {  
		Display.getDisplay( this ).setCurrent( commandForm );
	    } else if( c == tranlators ) {  
		Display.getDisplay( this ).setCurrent( tranAlert );
	    } else if( c == buts ) {  
		Display.getDisplay( this ).setCurrent( butsAlert );
	    } else if( c == delete ) {
		try {		    
		    RecordStore.deleteRecordStore( "hosts" );
		} catch ( javax.microedition.rms.RecordStoreException t ) {}
	    }
	}
    }

    protected void pauseApp() {
    }
    
    protected void destroyApp(boolean parm1) throws
	MIDletStateChangeException {
	try {
	    rs.closeRecordStore();
	} catch( javax.microedition.rms.RecordStoreException t ) {
	    
	}

    }
    
    protected void startApp() 
	throws javax.microedition.midlet.MIDletStateChangeException {

	Display.getDisplay( this ).setCurrent( about );
    }
}
